<template>
  <view class="order-form">
    <view class="img-content" v-if="imgShow">
      <view class="img-item-content" v-for="(img, index) in fileList" :key="index">
        <view>
          <img @click="review(index)" :src="img.url" alt="">
          <view @click="del(index)" v-if="editAble" class="del-icon">
            <uni-icons type="trash" size="14"></uni-icons>
          </view>
        </view>
      </view>
      <view class="img-item-content add" v-if="fileList.length < 5 && workId && ableUpload">
        <view>
          <view class="select" @click="selectImg">
            <uni-icons type="plusempty" size="30"></uni-icons>
          </view>
        </view>
      </view>
    </view>
    <view class="form-main-content">
      <uni-forms :modelValue="formData" ref="formData" v-if="initFinish" label-width="100" :rules="rules">
        <table>
          <tr>
            <td class="value">
              <uni-forms-item class="device-form" label="设备编号" :name="codeKey" :required="editAble">
                <view class="value-content">
                  <view class="device-no">
                    <view class="device-value">
                      <uni-easyinput type="text" v-model="formData[codeKey]" disabled />
                    </view>
                    <uni-icons type="scan" size="25" v-if="ableScan" @click="scanCode"></uni-icons>
                  </view>
                </view>
              </uni-forms-item>
            </td>
          </tr>
          <tr v-for="item in formList" :key="item.code">
            <td class="value">
              <uni-forms-item :label="item.name" :name="item.code" :required="item.required" label-width="100">
                <uni-easyinput :type="item.type || 'text'" v-model="formData[item.code]" :disabled="item.disable"
                               :placeholder="'请输入' + item.name" />
              </uni-forms-item>
            </td>
          </tr>
        </table>
        <view class="more-content" v-if="detailList.length > 0">
          <view class="line" :class="{ show: detailShow }" @click="detailShow = !detailShow">
            <uni-icons class="icon" type="arrowdown" size="16"></uni-icons>
          </view>
          <view class="detail-more" v-show="detailShow">
            <table>
              <tr v-for="item in detailList" :key="item.code">
                <td class="value">
                  <uni-forms-item :label="item.name" :name="item.code" :required="item.required" label-width="100">
                    <uni-easyinput :type="item.type || 'text'" v-model="formData[item.code]" :disabled="item.disable"
                                   :placeholder="'请输入' + item.name" />
                  </uni-forms-item>
                </td>
              </tr>
            </table>
          </view>
        </view>
      </uni-forms>
      <!-- <form ref="formData" v-if="initFinish">
        <table>
          <tr>
            <td class="key">设备编号</td>
            <td class="value">
              <view>
                <p v-if="!ableScan">{{formData.eqCode}}</p>
                <view class="device-no" v-if="ableScan">
                  <view class="device-value">
                    <input v-model="formData.eqCode" type="text" disabled>
                  </view>
                  <uni-icons type="scan" size="25"></uni-icons>
                </view>
              </view>
            </td>
          </tr>
          <tr v-for="item in formList" :key="item.code">
            <td class="key">{{item.name}}</td>
            <td class="value">
              <view>
                <input type="text" v-if="editAble && !item.type" v-model="formData[item.code]" :disabled="item.disable">
                <textarea v-if="editAble && item.type === 'textarea'" v-model="formData[item.code]"></textarea>
                <p v-if="!editAble">{{formData[item.code]}}</p>
              </view>
            </td>
          </tr>
        </table>
      </form> -->
    </view>
  </view>
</template>

<script>
  import {
    showConfirm,
    imgBaseUrl,
    getUrlParam,
  } from '@/utils/common';
  import wx from 'weixin-js-sdk';
  import {
    getEquipmentInfo,
  } from '../../../api/device/device.js';
  
  export default {
    props: {
      editAble: {
        type: Boolean,
        default: false,
      },
      formValue: {
        type: Object,
        default() {
          return {};
        },
      },
      workId: {
        type: [ String, Number ],
        default: '',
      },
      ableUpload: {
        type: Boolean,
        default: false,
      },
      imgShow: {
        type: Boolean,
        default: false,
      },
      ableScan: {
        type: Boolean,
        default: false,
      },
      formList: {
        type: Array,
        default() {
          return [];
        },
      },
      rules: {
        type: Object,
        default() {
          return {};
        },
      },
      codeKey: {
        type: String,
        default: 'eqCode',
      },
      detailList: {
        type: Array,
        default() {
          return [];
        },
      },
    },
    data() {
      return {
        fileList: [],
        formData: {},
        initFinish: false,
        detailShow: false,
      };
    },
    watch: {
      formValue: {
        immediate: true,
        deep: true,
        handler(value) {
          if (value.ztWorkorderPhotoList) {
            this.fileList = value.ztWorkorderPhotoList.map((val) => {
              return {
                url: `${imgBaseUrl}${val.photoUrl}`,
              };
            });
          }
        },
      },
    },
    created() {
      this.init();
    },
    methods: {
      async init() {
        await this.setFormData();
        this.initFinish = true;
        this.$nextTick(() => {
          const formData = this.$refs.formData[ 0 ] || this.$refs.formData;
          formData.setRules(this.rules);
        });
      },
      async setFormData() {
        const workerList = [];
        const {
          formList,
          formData,
          formValue,
          codeKey,
        } = this;
        formData[ codeKey ] = formValue[ codeKey ] || '';
        formList.forEach((val) => {
          if (!formData[ val.code ]) {
            formData[ val.code ] = formValue[ val.code ] || '';
          }
        });
        if (formValue.workEnginner1Name) {
          workerList.push(formValue.workEnginner1Name);
        }
        if (formValue.workEnginner2) {
          workerList.push(formValue.workEnginner2);
        }
        if (formValue.workEnginner3) {
          workerList.push(formValue.workEnginner3);
        }
        this.formData = {
          ...formValue,
          ...formData,
          worker: workerList.join(','),
        };
      },
      selectImg() {
        const that = this;
        uni.chooseImage({
          count: 1,
          success(e) {
            e.tempFiles.forEach((val, index) => {
              e.tempFiles[ index ].url = val.path;
            });
            that.imgToSmall(e.tempFiles);
          },
        });
      },
      imgToSmall(fileList) {
        const that = this;
        // that.fileList = [ ...that.fileList, ...fileList ];
        fileList.forEach((val) => {
          uni.getImageInfo({
            src: val.url,
            success: function (res) {
              const { width, height } = res;
              const img = new Image();
              img.src = val.url;
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              canvas.width = width;
              canvas.height = height;
              ctx.drawImage(img, 0, 0, width, height);
              const num = 500 / (val.size / 1000);
              const base64 = canvas.toDataURL(val.type, num > 1 ? 1 : num);
              const file = that.canvasToFile({
                baseUrl: base64,
                type: val.type,
                name: val.name,
              });
              that.fileList = [ ...that.fileList, file ];
            },
            fail: function () {
              that.$modal.showToast('上传失败~');
            },
          });
        });
      },
      canvasToFile(dataObj) {
        const { baseUrl, type, name } = dataObj;
        const urlArr = baseUrl.split('base64,');
        const realUrl = urlArr[ 1 ] || urlArr[ 0 ];
        const bytes = window.atob(realUrl);
        const ab = new ArrayBuffer(bytes.length);
        const ia = new Uint8Array(ab);
        for (let i = 0; i < bytes.length; i += 1) {
          ia[ i ] = bytes.charCodeAt(i);
        }
        const res = new Blob([ ab ], { type });
        const file = new File([ res ], name, { type });
        file.path = window.URL.createObjectURL(res);
        file.url = file.path;
        return file;
      },
      review(index) {
        const imgUrl = this.fileList.map((val) => {
          return val.url;
        });
        uni.previewImage({
          urls: imgUrl,
          current: index,
        });
      },
      async del(index) {
        const {
          fileList,
        } = this;
        const confirm = await showConfirm('确定删除该图片？');
        if (confirm.confirm) {
          fileList.splice(index, 1);
          this.fileList = fileList;
        }
      },
      formReset() {
      },
      async getFormData() {
        const keys = this.formList.map((val) => {
          return val.code;
        });
        keys.unshift(this.codeKey);
        const resultObj = {};
        let isSuccess = true;
        const formData = this.$refs.formData[ 0 ] || this.$refs.formData;
        const res = await formData.validate().catch(() => {
          isSuccess = false;
        });
        if (res) {
          keys.forEach((val) => {
            if (res[ val ]) {
              resultObj[ val ] = res[ val ];
            }
          });
        }
        console.log(resultObj);
        return {
          isSuccess,
          formData: resultObj,
        };
      },
      getFileList() {
        const {
          fileList,
        } = this;
        return {
          fileList,
        };
      },
      scanCode() {
        const { codeKey } = this;
        wx.scanQRCode({
          needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
          scanType: [ 'qrCode' ], // 可以指定扫二维码还是一维码，默认二者都有
          success(res) {
            if (res.resultStr) {
              const resultParam = getUrlParam(res.resultStr);
              this.formData[ codeKey ] = resultParam.eqCode || res.resultStr;
              this.getDeviceInfo();
            }
          },
          fail(response) {
            this.$modal.showToast('扫码失败~');
          },
        });
      },
      async getDeviceInfo() {
        const { codeKey } = this;
        const param = {};
        param[ codeKey ] = this.formData[ codeKey ];
        const res = await getEquipmentInfo(param);
        if (res.code === 200) {
          res.data = res.data || {};
          this.formData = {
            ...this.formData,
            eqName: res.data.eqName,
          };
        }
      },
    },
  };
</script>

<style lang="scss">
  .order-form {
    .img-content {
      margin: 0 -5px;
      margin-bottom: 15px;
      
      .img-item-content {
        width: 20%;
        float: left;
        padding: 0 5px;
        height: calc(((100vw - 20px) / 5) - 10px);
        text-align: center;
        
        > view {
          position: relative;
          border: 1px solid #ddd;
          border-radius: 4px;
          height: 100%;
          
          img {
            display: block;
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .del-icon {
            position: absolute;
            top: 0;
            right: 0;
            background-color: rgba(0, 0, 0, 0.5);
            padding: 3px;
            border-radius: 3px;
            width: 20px;
            height: 20px;
            
            uni-text {
              color: white !important;
              display: block;
              line-height: 1;
            }
          }
        }
        
        &.add {
          > view {
            .select {
              height: 100%;
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: center;
              
              uni-text {
                color: #ddd !important;
              }
            }
          }
        }
      }
      
      &::after {
        display: block;
        content: "";
        clear: both;
      }
    }
    
    .form-main-content {
      .uni-forms {
        table {
          width: 100%;
          border-collapse: collapse;
          
          tr {
            td {
              padding: 10px;
              border-bottom: 1px solid #ddd;
              
              &.value {
                width: 100%;
                
                .uni-forms-item {
                  
                  p {
                    font-size: 14px;
                    line-height: 1.5;
                  }
                  
                  .device-no {
                    display: flex;
                    align-items: center;
                    width: 100%;
                    
                    .device-value {
                      flex: 1;
                    }
                    
                    .uni-icons {
                      display: block;
                      color: #ddd !important;
                      margin-left: 10px;
                    }
                  }
                  
                  uni-textarea {
                    width: 100%;
                  }
                  
                  /deep/ .uni-easyinput__content {
                    &.is-disabled {
                      background-color: white !important;
                      color: rgb(51, 51, 51);
                    }
                  }
                  
                  &.device-form {
                    .value-content {
                      height: 100%;
                      align-items: center;
                      display: flex;
                    }
                  }
                }
              }
              
            }
          }
        }
        .more-content {
          .line {
            text-align: center;
            padding: 5px 0;
            margin: 0 -10px;
            background-color: #f1f1f1;
            .icon {
              display: inline-block;
              transition: all 0.3s;
            }
            &.show {
              .icon {
                transform: rotateZ(180deg);
              }
            }
          }
        }
      }
    }
    
  }
</style>
